package com.chenglong.supermarket.chenglongsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.chenglong.supermarket.chenglongsearch.config.ChenglongMallElasticsearchConfig;
import com.chenglong.supermarket.chenglongsearch.constant.EsConstant;
import com.chenglong.supermarket.chenglongsearch.service.ProductSaveService;
import com.chenglong.supermarket.common.to.es.SkuEsModel;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: cheng-long-mall
 * @description:
 * @author: JIANGBEI
 * @create: 2021-05-10 20:43
 **/
@Service
public class ProductSaveServiceImpl implements ProductSaveService {
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Override
    public void productStatusUp(List<SkuEsModel> skuEsModelList) throws IOException {
        //保存到ES
        //1.建立一个索引product,建立好映射关系

        //2.给ES中保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModelList) {
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            indexRequest.source(s, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = restHighLevelClient.bulk(bulkRequest, ChenglongMallElasticsearchConfig.COMMON_OPTIONS);
        List<String> ids = Arrays.stream(bulk.getItems()).map(item -> {
            String id = item.getId();
            return id;
        }).collect(Collectors.toList());
        //todo 如果批量错误
        bulk.hasFailures();
        //打印日志记录出来
        //或者记录数据库，看是否上架成功
    }
}
